<template>
  <div>
      <div class='div'>
        <table>
            <tr>
                <td>选择</td>
                <td>商品</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>库存</td>
            </tr>
            <tr v-for='item,index in goods'>
                <td><input type="checkbox"  v-model="check_list"  :value="index"></td>
                <td>{{item.name}}</td>
                <td>{{item.price}}元</td>
                <td><input type="number" v-model="cart[index].num"   @change="watch_num(cart[index].num,index)"></td>
                <td>{{item.num}}</td>
            </tr>
        </table>
        <button @click="buy">购买</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    data(){
        return{
            goods:[],
            cart:[],
            num:0,
            check_list:[],
        }
    },
    created(){
        this.get_goods()
    },
    methods:{
        get_goods(){
            axios.get('http://127.0.0.1:8000/myapp/show/').then(res=>{
                this.goods = res.data.data
                // 用于数量判断的list
                for(let i=0;i<this.goods.length;i++){
                    this.cart.push({
                        name : this.goods[i].name,
                        price: this.goods[i].price,
                        num: 1
                    })
                }
            })
        },
        buy(){
            // 打包购物车参数
            var good=[]
            for(let i=0;i<this.check_list.length;i++){
                good.push(this.cart[this.check_list[i]])
            }
            // 方便传参 使用json字符串
            var str_cart= JSON.stringify(good)
            sessionStorage.setItem('cart',str_cart)
            this.$router.push({name:'details'})
        },
        watch_num(num,index){
            if (num>this.goods[index].num){
                alert('购买数量过多')
                // 清零
                this.cart[index].num = 1
            }else if(num<1){
                alert('购买数量至少为1')
                // 清零
                this.cart[index].num = 1
            }
            
        }
    }
    
}
</script>

<style>
.div{
    margin-left: 40%;
}
</style>